<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/28
 * Time: 18:56
 *
 */

class WinxinSdk
{

    private $appID = "wx94010b1eb2f5362d";
    private $appsecret = "51ac1f02b2cc1c5a643c85f908acb680";
    public static $access_token = "";//也可以写入session
    public static $expires_in = 0;//token失效时间

    public function WinxinSdk($appID,$appsecret)
    {
        $this->appID = $appID;
        $this->appsecret = $appsecret;


    }
    public function getToken()
    {//获取token
        $token = '';

        if(self::$access_token=="" && time()>self::$expires_in-360)//差十分钟获取就重新获取新的
        {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appID&secret=$this->appsecret";
            $token = $this->curlGet($url);
            $token = json_decode($token);
            if(isset($token->access_token))
            {
                self::$access_token = $token->access_token;
                self::$expires_in = time()+$token->expires_in;
                return  $token->access_token;
            }
            else
            {
                return false;
            }
        }

        return false;

    }
    /*
     * reposeMsg 没封装好呢
     */
    public function reposeMsg()
    {//接收事件推送过来的数据，并回复
        //文案地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140453
        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        //获取到xml数据后，处理消息类型，并设置回复消息内容(回复就是直接打印xml数据)
        //数据格式
        $arr = simplexml_load_string($postArr);
        if(strtolower($arr->MsgType)=="event")
        {
            $toUser = $arr->ToUserName;
            $foUser = $arr->FromUserName;
            $msgType = 'text';
            $createTime = time();
            $content = '尊敬的'.$foUser."谢谢你的关注\n";

            if(strtolower($arr->Event)=="subscribe")
            {//订阅
                $temp = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
                $temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
                return $temp;
            }
        }
    }
    /*
   * textMsg 没封装好呢
   */
    public function textMsg()
    {//接收文本，并回复
        //文案地址:
        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        //获取到xml数据后，处理消息类型，并设置回复消息内容(回复就是直接打印xml数据)
        //数据格式
        $arr = simplexml_load_string($postArr);
        if(strtolower($arr->MsgType)=='text')
        {
            $toUser = $arr->ToUserName;
            $foUser = $arr->FromUserName;
            $msgType = 'text';
            $createTime = time();
            $content = $arr->Content."888888".$toUser."\n";

            $temp = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
            $temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
            return $temp;

        }

    }
    /*
    * getQR 没封装好呢
    */
    public function  getQR($data = null)
    {//获取二维码
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".self::$access_token;
        $jsonData = '{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}';
        $res = $this->curlPost2($url,$jsonData);
        return $res;
    }

    public function customMenu($data)
    {//自定义菜单
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".self::$access_token;

        $res = $this->curlPost2($url,$data);
        return $res;
    }
    public function onclickMenu()
    {//点击自定义菜单市出发内容
        //$postArr = file_get_contents("php://input");
        $postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
        $arr = simplexml_load_string($postArr);
        //$this->logs('inclickMenu.txt',(array)$arr->ToUserName);
        if(strtolower($arr->MsgType)=="event")
        {
            if(strtolower($arr->Event)=="click")
            {
                //接受消息格式
                $rtemp = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[FromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[CLICK]]></Event><EventKey><![CDATA[EVENTKEY]]></EventKey></xml>";
                //推送文本格式
                $temp = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[%s]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
                $toUser = $arr->ToUserName;
                $foUser = $arr->FromUserName;
                $msgType = 'text';
                $content = '你点击了--'.$arr->EventKey;
                $createTime = time();
                $temp = sprintf($temp,$foUser,$toUser,$createTime,$msgType,$content);
                return $temp;


            }
        }


    }





    public function curlGet($url)
    {//get请求接口
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        $data = curl_exec($ch);
        $httpCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
        curl_close($ch);
        return ($httpCode>=200 && $httpCode<300) ? $data:false;
    }
    public function curlPost($url,$data = null)
    {//post请求接口
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return  $output;

    }
    public function curlPost2($url,$data)
    {//第一个post方法
        //$data = http_build_query($data);
        $opts = array (
            'http' => array (
                'method' => 'POST',
                'header'=> "Content-type: application/x-www-form-urlencodedrn",
                "Content-Length: " . strlen($data) . "rn",
                'content' => $data
            )
        );

        $context = stream_context_create($opts);
        $html = file_get_contents($url, false, $context);
        return $html;

    }
    public function logs($file,$data)
    {//打印日志
        (is_array($data))?$data = print_r($data,true):$data;
        file_put_contents($file,$data);
    }




}